package com.sl.hx.shop.ui.mine;


import android.Manifest;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.baichuan.android.trade.AlibcTrade;
import com.alibaba.baichuan.android.trade.AlibcTradeSDK;
import com.alibaba.baichuan.android.trade.callback.AlibcTradeCallback;
import com.alibaba.baichuan.android.trade.model.AlibcShowParams;
import com.alibaba.baichuan.android.trade.model.OpenType;
import com.alibaba.baichuan.android.trade.page.AlibcBasePage;
import com.alibaba.baichuan.android.trade.page.AlibcMyCartsPage;
import com.alibaba.baichuan.android.trade.page.AlibcMyOrdersPage;
import com.alibaba.baichuan.trade.biz.context.AlibcTradeResult;
import com.bumptech.glide.Glide;
import com.sl.hx.shop.MainActivity;
import com.sl.hx.shop.R;
import com.sl.hx.shop.base.BaseFragment;
import com.sl.hx.shop.bean.HeadBean;
import com.sl.hx.shop.bean.MessageBean;
import com.sl.hx.shop.constant.SPUKey;
import com.sl.hx.shop.ui.mine.activity.AboutActivity;
import com.sl.hx.shop.ui.mine.activity.HistoryActivity;
import com.sl.hx.shop.ui.mine.activity.LoginActivity;
import com.sl.hx.shop.ui.mine.activity.MessageActivity;
import com.sl.hx.shop.ui.mine.activity.QuestionActivity;
import com.sl.hx.shop.ui.mine.activity.SettingActivity;
import com.sl.hx.shop.ui.mine.contacts.MineContacts;
import com.sl.hx.shop.ui.mine.presnter.MinePresenter;
import com.sl.hx.shop.utils.ConfigUtil;
import com.sl.hx.shop.utils.NotifySetting;
import com.sl.hx.shop.utils.SPUtils;
import com.sl.hx.shop.utils.ToastUtil;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import q.rorbin.badgeview.Badge;
import q.rorbin.badgeview.QBadgeView;

import static android.app.Activity.RESULT_OK;
import static com.sl.hx.shop.constant.AppConfig.ID;

public class MineFragment extends BaseFragment<MineContacts.view, MinePresenter> implements MineContacts.view {


    @BindView(R.id.iv_msg)
    ImageView ivMsg;
    @BindView(R.id.iv_setting)
    ImageView ivSetting;
    @BindView(R.id.rl_topbg)
    RelativeLayout rlTopbg;
    @BindView(R.id.tv_notice)
    TextView tvNotice;
    @BindView(R.id.tv_firsttime)
    TextView tvFirsttime;
    @BindView(R.id.rl_notice)
    RelativeLayout rlNotice;
    @BindView(R.id.iv_share)
    ImageView ivShare;
    @BindView(R.id.tv_share)
    TextView tvShare;
    @BindView(R.id.rl_share)
    RelativeLayout rlShare;
    @BindView(R.id.iv_score)
    ImageView ivScore;
    @BindView(R.id.tv_score)
    TextView tvScore;
    @BindView(R.id.rl_score)
    RelativeLayout rlScore;
    @BindView(R.id.iv_problem)
    ImageView ivProblem;
    @BindView(R.id.tv_problem)
    TextView tvProblem;
    @BindView(R.id.rl_problem)
    RelativeLayout rlProblem;
    @BindView(R.id.iv_about)
    ImageView ivAbout;
    @BindView(R.id.tv_about)
    TextView tvAbout;
    @BindView(R.id.rl_about)
    RelativeLayout rlAbout;
    @BindView(R.id.ll_set)
    LinearLayout llSet;
    @BindView(R.id.my_head)
    ImageView myhead;


    private AlibcShowParams alibcShowParams;//页面打开方式，默认，H5，Native
    private Map<String, String> exParams;//yhhpass参数
    private List<MessageBean> messageList = new ArrayList<>();

    @Override
    protected MinePresenter createPresenter() {
        return new MinePresenter(mContext);
    }

    @Override
    protected int getViewLayoutId() {
        return R.layout.fragment_mine;
    }

    @Override
    protected void initView(View mView) {
        //用户信息
        if (SPUtils.getInstance().getString(ID)!=null&&!TextUtils.isEmpty(SPUtils.getInstance().getString(ID))){
            mPresenter.getHead();
        }
        //消息通知
        mPresenter.getMessage();
        alibcShowParams = new AlibcShowParams(OpenType.Native, false);
        exParams = new HashMap<>();
        exParams.put("isv_code", "appisvcode");
        exParams.put("alibaba", "杭州圣利");//自定义参数部分，可任意增删改
    }

    @Override
    public void onResume() {
        super.onResume();
        //判断消息通知是否开启
        if (isNotificationEnabled()) {
            rlNotice.setVisibility(View.GONE);
        } else {
            rlNotice.setVisibility(View.VISIBLE);
        }
    }

    @OnClick({R.id.iv_setting, R.id.order, R.id.shopcar, R.id.collection, R.id.browse_records, R.id.iv_msg,
            R.id.msg_close, R.id.rl_share, R.id.rl_score, R.id.rl_problem, R.id.rl_about, R.id.rl_notice, R.id.my_head})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            //设置
            case R.id.iv_setting:
                islogin(SettingActivity.class);
                break;
            //订单
            case R.id.order:
                if (ConfigUtil.isLogin()) {
                    AlibcBasePage ordersPage = new AlibcMyOrdersPage(0, true);
                    AlibcTrade.show(getActivity(), ordersPage, alibcShowParams, null, exParams,
                            new AlibcTradeCallback() {
                                @Override
                                public void onTradeSuccess(AlibcTradeResult alibcTradeResult) {

                                }

                                @Override
                                public void onFailure(int i, String s) {

                                }
                            });
                } else {
                    toActivity(LoginActivity.class);
                }
                break;
            //购物车
            case R.id.shopcar:
                if (ConfigUtil.isLogin()) {
                    AlibcBasePage myCartsPage = new AlibcMyCartsPage();
                    AlibcTrade.show(getActivity(), myCartsPage, alibcShowParams, null, exParams,
                            new AlibcTradeCallback() {
                                @Override
                                public void onTradeSuccess(AlibcTradeResult alibcTradeResult) {
                                }

                                @Override
                                public void onFailure(int code, String msg) {
                                    //打开电商组件，用户操作中错误信息回调。code：错误码；msg：错误信息
                                }
                            });
                } else {
                    toActivity(LoginActivity.class);
                }
                break;
            case R.id.collection:
                if (ConfigUtil.isLogin()) {
                    MainActivity mainActivity = (MainActivity) getActivity();
                    mainActivity.setTabSelection(2);
                } else {
                    toActivity(LoginActivity.class);
                }
                break;
            //历史记录
            case R.id.browse_records:
                    toActivity(HistoryActivity.class);
                break;
            case R.id.rl_notice:
                //跳转设置页开启通知
                NotifySetting.gotoNotifySet(mContext);
                break;
            //消息通知
            case R.id.iv_msg:
                    Intent intent = new Intent(getActivity(), MessageActivity.class);
                    Bundle args = new Bundle();
                    args.putSerializable("MESSAGELIST", (Serializable) messageList);
                    intent.putExtra("MESSAGBUNDLE", args);
                    startActivity(intent);
                    ivMsg.setImageResource(R.drawable.massage);
                break;
            case R.id.rl_share:
                Intent textIntent = new Intent(Intent.ACTION_SEND);
                textIntent.setType("text/plain");
                textIntent.putExtra(Intent.EXTRA_TEXT, "http://u4793818.viewer.maka.im/k/A0H96V8I");
                startActivity(Intent.createChooser(textIntent, "分享"));
                break;
            //打分好评
            case R.id.rl_score:
                try {
                    Uri uri = Uri.parse("market://details?id=" + "com.sl.hx.shop");
                    Intent intent1 = new Intent(Intent.ACTION_VIEW, uri);
                    intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent1);
                } catch (Exception e) {
                    ToastUtil.showShort(mActivity, "您的手机没有安装Android应用市场");
                    e.printStackTrace();
                }
                break;
            //常见问题
            case R.id.rl_problem:
                toActivity(QuestionActivity.class);
                break;
            //关于我们
            case R.id.rl_about:
                toActivity(AboutActivity.class);
                break;
            //头像
            case R.id.my_head:
                islogin(SettingActivity.class);
                break;
            case R.id.msg_close:
                rlNotice.setVisibility(View.GONE);
                break;
        }
    }

    private void islogin(Class<?> activity) {
        if (ConfigUtil.isLogin()) {
            toActivity(activity);
        } else {
            toActivity(LoginActivity.class);
        }
    }


    @Override
    public void ShowHead(HeadBean headBean) {
        Glide.with(mActivity).load(headBean.getLogo()).into(myhead);
    }

    @Override
    public void ShowMessage(List<MessageBean> messageBean) {
        messageList.addAll(messageBean);

        //本地消息条数比新数据小的话,显示新消息通知
        if (SPUtils.getInstance().getInt(SPUKey.MESSAGE_COUNT) < messageBean.size()) {
            ivMsg.setImageResource(R.drawable.massage_new);
        } else {
            ivMsg.setImageResource(R.drawable.massage);
        }
        SPUtils.getInstance().put(SPUKey.MESSAGE_COUNT, messageBean.size());
    }

    private boolean isNotificationEnabled() {
        NotificationManagerCompat notification = NotificationManagerCompat.from(getActivity());
        boolean isEnabled = notification.areNotificationsEnabled();
        SPUtils.getInstance().put(SPUKey.ISRECEIVEMESSAGE, true);
        return isEnabled;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //调用了AlibcTrade.show方法的Activity都需要调用AlibcTradeSDK.destory()
        AlibcTradeSDK.destory();
    }
}
